package com.tao.design.single

/**
 *
 * @ProjectName:    ros
 * @Package:        com.xxl.roslib.base
 * @ClassName:      SingletonHolder
 * @Description:     java类作用描述
 * @Author:         wangxf
 * @CreateDate:     2022/3/4 17:50
 * @UpdateUser:     更新者
 * @UpdateDate:     2022/3/4 17:50
 * @UpdateRemark:   更新说明
 * @Version:        1.0
 */
//::双冒号操作符 表示把一个方法当做一个参数，传递到另一个方法中进行使用，通俗的来讲就是引用一个方法。先来看一下例子：
open class SingleParam<out T, in A>(creator: (A) -> T) {
    private var creator: ((A) -> T)? = creator

    @Volatile
    private var instance: T? = null

    fun getInstance(arg: A): T {
        val i = instance
        if (i != null) {
            return i
        }

        return synchronized(this) {
            val i2 = instance
            if (i2 != null) {
                i2
            } else {
                val created = creator!!(arg)
                instance = created
                creator = null
                created
            }
        }
    }

}

open class Single<out T>(creator: () -> T) {
    private var creator: (() -> T)? = creator

    @Volatile
    private var instance: T? = null

    fun getInstance(): T {
        val i = instance
        if (i != null) {
            return i
        }

        return synchronized(this) {
            val i2 = instance
            if (i2 != null) {
                i2
            } else {
                val created = creator!!()
                instance = created
                creator = null
                created
            }
        }
    }
}
/*

其他普通 单例写法

1饿汉单例
object SingletonDemo

2懒汉单例
class SingletonDemo private constructor() {
    companion object {
        private var instance: SingletonDemo? = null
         //这里使用的是自定义访问器
            get() {
                if (field == null) {
                    field = SingletonDemo()
                }
                return field
            }

        fun get(): SingletonDemo{
         return instance!!
        }
    }
}

3线程安全的懒汉单例
class SingletonDemo private constructor() {
    companion object {
        private var instance: SingletonDemo? = null
            get() {
                if (field == null) {
                    field = SingletonDemo()
                }
                return field
            }
            //使用同步锁注解
        @Synchronized
        fun get(): SingletonDemo{
            return instance!!
        }
    }

}

4双重校验锁
class SingletonDemo private constructor() {
    companion object {
        val instance: SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            SingletonDemo() }
    }
}

5静态内部类
class SingletonDemo private constructor() {
    companion object {
        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder= SingletonDemo()
    }
}


 */


